package com.jdls.tanhua.interceptor;

import com.jdls.tanhua.commons.utils.JwtUtils;
import com.jdls.tanhua.pojo.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 嘉德罗斯
 * @date 2021/10/24
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("访问了:"+request.getRequestURI());
        String header = request.getHeader("Authorization");
        boolean b = JwtUtils.get(header);
        if(!b){
            response.setStatus(401);
            return false;
        }

        Claims body = JwtUtils.getBody(header);
        Long id =Long.valueOf ((Integer) body.get("id"));
        String phone = (String) body.get("phone");
        User user = new User();
        user.setId(id);
        user.setMobile(phone);
        UserHolder.set(user);
        return true;
    }
}
